﻿using Framework.EncryptionDecryptionService.Abstract;
using Framework.EncryptionDecryptionService.Attributes;
using Framework.EncryptionDecryptionService.Enums;
using Framework.EncryptionDecryptionService.Helpers;
using Framework.EncryptionDecryptionService.Inteface;
using System.Security.Cryptography;

namespace Framework.EncryptionDecryptionService.Achieve
{
    /// <summary>
    /// RSA加密服务
    /// </summary>
    /// <remarks>
    /// 使用方式：
    /// <para>1、注入：通过注入获取到的RSA加密服务生命周期跟随API的生命周期，且RSA秘钥在整个API的生命周期内不变</para>
    /// <para>2、实例：通过实例生成的RSA加密服务周期为当前实例的生命周期，此时RSA秘钥需要重新生成，且秘钥生命周期与实例RSA加密服务生命周期一致</para>
    /// </remarks>
    [Encryption(EncryptionAlgorithm.RSA)]
    public sealed class EncryptionServiceRsa : AbsEncryptionService
    {
        /// <summary>
        /// RSA加密服务
        /// </summary>
        /// <param name="secretKey">RSA秘钥</param>
        /// <remarks>实例：通过实例生成的RSA加密服务周期为当前实例的生命周期，此时RSA秘钥需要重新生成，且秘钥生命周期与实例RSA加密服务生命周期一致</remarks>
        public EncryptionServiceRsa(SecretKeyServiceRsa secretKey = null) : base(secretKey ?? new SecretKeyServiceRsa())
        {
        }

        public override byte[] Encrypt(string data)
        {
            data ??= "";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(SecretKey.PublicSecretKey);
                byte[] plainBytes = data.ConvertToBytes();
                // 使用公钥进行加密
                byte[] bytes = rsa.Encrypt(plainBytes, false);
                //var dataDecrypt = rsa.Decrypt(bytes.ToBase64String().FromBase64String(), false).ConvertToString();
                return bytes;
            }
        }
    }
}
